﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ERPStore.Extensions;

using Microsoft.Practices.Unity;

namespace ERPStore.NewsLetters.EventConsumers
{
	public class ApplicationStartEventConsumer : EventBrokR.IConsumer<ERPStore.Events.ApplicationStartedEvent>
	{
		#region IConsumer<ApplicationStartedEvent> Members

		public void Handle(ERPStore.Events.ApplicationStartedEvent eventMessage)
		{
			var Container = ERPStore.GlobalConfiguration.Configuration.DependencyResolver.GetContainer();

			var settings = Container.Resolve<Models.Settings>();
			if (settings.RepositoryName != "mock")
			{
				var initializer = Container.Resolve<CloudSoft.Repositories.IRepositoryInitializer>("newsletterssqlschemainitializer");
				if (initializer != null)
				{
					initializer.Initialize("_erpstore_schema_newsletters");
				}
			}

			if (ERPStore.GlobalConfiguration.Configuration.HosterName == "SvcHost")
			{
				var taskService = Container.Resolve<ERPStore.Services.IScheduledTaskService>();

				var task = new ERPStore.Models.TaskEntry();
				task.Period = ERPStore.Models.ScheduledTaskTimePeriod.Minute;
				task.Interval = 5;
				task.Name = "NewsletterSenderChecker";
				task.IsParallelizable = true;
				var parameters = new Dictionary<string, object>();
				parameters.Add("Settings", settings);
				task.WorkflowProperties = parameters;
				task.GetActivityInstance = () => new Workflows.EmailSender();
				taskService.Add(task);
			}
		}

		#endregion
	}
}
